package cn.gailvlun.gll.presentation.base;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.trello.rxlifecycle2.components.support.RxFragment;

import cn.gailvlun.gll.util.LogUtil;



public abstract class BaseFragment extends RxFragment {

    public Context mContext;

    
    
    private boolean isInited = false;
    
    private boolean isLoaded = false;
    
    protected boolean isVisi = false;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = getContext();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = initComponent(inflater, container);

        createHandler();

        if (isLazyLoad()) {
            if (isVisi && !isInited && !isLoaded) {
                isInited = true;
                isLoaded = true;
                loadData(savedInstanceState);
            } else {
                
                isInited = true;
            }
        } else {
            loadData(savedInstanceState);
        }
        return view;
    }

    protected abstract View initComponent(@NonNull LayoutInflater inflater, @Nullable ViewGroup container);

    protected abstract void createHandler();

    protected abstract void loadData(@Nullable Bundle savedInstanceState);

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isLazyLoad()) {
            if (isLoaded) {
                if (isVisibleToUser) {
                    onVisible();
                } else {
                    onInVisible();
                }
            }
            if (isVisibleToUser) {
                isVisi = true;
                if (isInited && !isLoaded) {
                    isLoaded = true;
                    loadData(null);
                }
            } else {
                isVisi = false;
            }
        }
    }

    
    protected boolean isLazyLoad() {
        return false;
    }

    protected void onVisible() {
        LogUtil.d("onVisible");
    }

    protected void onInVisible() {
        LogUtil.d("onInVisible");
    }
}
